<!--
 * @Author: AI Assistant
 * @Description: User Center Component for regular users
-->
<template>
  <div class="user-center-container">
    <el-card class="user-card">
      <div class="user-header">
        <div class="avatar-container">
          <el-avatar :size="100" :src="userInfo.headimgurl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"></el-avatar>
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="uploadAvatar"
            :show-file-list="false"
            accept="image/*">
            <el-button size="small" type="primary" class="upload-btn">更换头像</el-button>
          </el-upload>
        </div>
        <div class="user-info">
          <h2>{{ userInfo.nickname || userInfo.username }}</h2>
          <p>注册时间: {{ formatDate(userInfo.registerTime) }}</p>
        </div>
      </div>
      
      <el-divider />
      
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>
        
        <el-form-item label="密码">
          <el-button type="primary" @click="showChangePasswordDialog">修改密码</el-button>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="updateProfile">保存修改</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="500px">
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码" show-password />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updatePassword">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from '@/js/axios'
import { getUserInfo } from '@/js/public'

export default {
  name: 'UserCenter',
  setup() {
    // 用户信息
    const userInfo = ref({})
    
    // 表单数据
    const form = reactive({
      username: '',
      nickname: '',
    })
    
    // 表单规则
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { max: 20, message: '长度不能超过 20 个字符', trigger: 'blur' }
      ]
    }
    
    // 密码表单
    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    // 密码表单规则
    const passwordRules = {
      oldPassword: [
        { required: true, message: '请输入原密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== passwordForm.newPassword) {
              callback(new Error('两次输入密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }
    
    const formRef = ref(null)
    const passwordFormRef = ref(null)
    const passwordDialogVisible = ref(false)
    
    // 获取用户信息
    const loadUserInfo = async () => {
      try {
        const type = localStorage.getItem('currentLoginType') || 'user'
        const storedInfo = JSON.parse(localStorage.getItem(`userInfo_${type}`))
        
        if (storedInfo) {
          userInfo.value = storedInfo
          
          // 填充表单
          form.username = storedInfo.username || ''
          form.nickname = storedInfo.nickname || ''
        }
        
        // 从服务器获取最新数据
        const res = await axios.get('/user/profile')
        if (res.data.code === 200) {
          userInfo.value = res.data.data
          
          // 更新表单
          form.username = res.data.data.username || ''
          form.nickname = res.data.data.nickname || ''
          
          // 更新本地存储
          localStorage.setItem(`userInfo_${type}`, JSON.stringify(res.data.data))
        }
      } catch (error) {
        console.error('获取用户信息失败', error)
      }
    }
    
    // 更新用户信息
    const updateProfile = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            const res = await axios.put('/user/profile', {
              username: form.username,
              nickname: form.nickname
            })
            
            if (res.data.code === 200) {
              ElMessage.success('个人信息更新成功')
              await loadUserInfo()
            } else {
              ElMessage.error(res.data.msg || '更新失败')
            }
          } catch (error) {
            ElMessage.error('更新失败，请重试')
            console.error(error)
          }
        }
      })
    }
    
    // 重置表单
    const resetForm = () => {
      if (formRef.value) {
        formRef.value.resetFields()
        
        // 重置为当前用户信息
        form.username = userInfo.value.username || ''
        form.nickname = userInfo.value.nickname || ''
      }
    }
    
    // 显示修改密码对话框
    const showChangePasswordDialog = () => {
      passwordDialogVisible.value = true
      
      // 重置密码表单
      if (passwordFormRef.value) {
        passwordFormRef.value.resetFields()
      }
    }
    
    // 更新密码
    const updatePassword = async () => {
      if (!passwordFormRef.value) return
      
      await passwordFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            const res = await axios.put('/user/password', {
              oldPassword: passwordForm.oldPassword,
              newPassword: passwordForm.newPassword
            })
            
            if (res.data.code === 200) {
              ElMessage.success('密码修改成功')
              passwordDialogVisible.value = false
            } else {
              ElMessage.error(res.data.msg || '密码修改失败')
            }
          } catch (error) {
            ElMessage.error('修改失败，请重试')
            console.error(error)
          }
        }
      })
    }
    
    // 上传头像
    const uploadAvatar = async (options) => {
      const formData = new FormData()
      formData.append('file', options.file)
      
      try {
        const res = await axios.post('/user/avatar', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        
        if (res.data.code === 200) {
          ElMessage.success('头像上传成功')
          
          // 更新用户信息
          await loadUserInfo()
        } else {
          // 静默处理头像上传失败，不显示错误信息
console.log('头像上传失败:', res.data.msg || '头像上传失败')
        }
      } catch (error) {
        // 静默处理头像上传失败，不显示错误信息
        console.error('头像上传失败:', error)
      }
    }
    
    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return '未知'
      
      try {
        const date = new Date(dateStr)
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
      } catch (e) {
        return dateStr
      }
    }
    
    onMounted(() => {
      loadUserInfo()
    })
    
    return {
      userInfo,
      form,
      rules,
      passwordForm,
      passwordRules,
      formRef,
      passwordFormRef,
      passwordDialogVisible,
      updateProfile,
      resetForm,
      showChangePasswordDialog,
      updatePassword,
      uploadAvatar,
      formatDate
    }
  }
}
</script>

<style lang="scss" scoped>
.user-center-container {
  max-width: 900px;
  margin: 0 auto;
  
  .user-card {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 6px 25px rgba(0, 0, 0, 0.06);
    border: 1px solid rgba(255, 255, 255, 0.8);
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    }
    
    :deep(.el-card__body) {
      padding: 25px;
    }
    
    .user-header {
      display: flex;
      margin-bottom: 30px;
      
      .avatar-container {
        position: relative;
        margin-right: 40px;
        display: flex;
        flex-direction: column;
        align-items: center;
        
        :deep(.el-avatar) {
          border: 3px solid #fff;
          box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
          margin-bottom: 15px;
          transition: all 0.3s ease;
          
          &:hover {
            transform: scale(1.05);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
          }
        }
        
        .avatar-uploader {
          .upload-btn {
            border-radius: 20px;
            font-weight: 500;
            padding: 8px 15px;
            border: none;
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            transition: all 0.3s;
            
            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 5px 15px rgba(79, 172, 254, 0.25);
            }
            
            &:active {
              transform: translateY(0);
            }
          }
        }
      }
      
      .user-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        
        h2 {
          margin-bottom: 12px;
          font-size: 28px;
          color: #2c3e50;
          font-weight: 600;
        }
        
        p {
          margin: 5px 0;
          color: #606266;
          font-size: 15px;
          display: flex;
          align-items: center;
          
          &::before {
            content: '\f017'; /* Font Awesome clock icon */
            font-family: FontAwesome;
            margin-right: 8px;
            color: #909399;
          }
        }
      }
    }
    
    :deep(.el-divider) {
      margin: 25px 0;
    }
    
    :deep(.el-form) {
      max-width: 600px;
      
      .el-form-item {
        margin-bottom: 22px;
        
        .el-form-item__label {
          font-weight: 500;
          color: #2c3e50;
        }
        
        .el-input__wrapper {
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03), 0 0 0 1px rgba(0, 0, 0, 0.05) inset;
          border-radius: 8px;
          transition: all 0.3s;
          
          &:hover {
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05), 0 0 0 1px rgba(0, 0, 0, 0.08) inset;
          }
          
          &.is-focus {
            box-shadow: 0 2px 12px rgba(79, 172, 254, 0.1), 0 0 0 1px #4facfe inset;
          }
        }
        
        .el-button {
          border-radius: 8px;
          font-weight: 500;
          transition: all 0.3s;
          
          &.is-primary {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            border: none;
            padding: 12px 22px;
            
            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 5px 15px rgba(79, 172, 254, 0.25);
            }
            
            &:active {
              transform: translateY(0);
            }
          }
          
          &:not(.is-primary) {
            border: 1px solid #dcdfe6;
            padding: 11px 22px;
            
            &:hover {
              border-color: #c0c4cc;
              color: #409eff;
              background-color: rgba(236, 245, 255, 0.5);
            }
          }
        }
      }
    }
  }
  
  :deep(.el-dialog) {
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 10px 50px rgba(0, 0, 0, 0.15);
    
    .el-dialog__header {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      padding: 15px 20px;
      
      .el-dialog__title {
        color: #fff;
        font-size: 18px;
        font-weight: 600;
      }
      
      .el-dialog__headerbtn {
        .el-dialog__close {
          color: #fff;
          font-size: 20px;
          
          &:hover {
            color: rgba(255, 255, 255, 0.8);
          }
        }
      }
    }
    
    .el-dialog__body {
      padding: 25px 20px;
    }
    
    .dialog-footer {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
      
      .el-button {
        border-radius: 8px;
        font-weight: 500;
      }
      
      .el-button--primary {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        border: none;
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .user-center-container {
    padding: 0;
    
    .user-card {
      border-radius: 10px;
      
      :deep(.el-card__body) {
        padding: 20px 15px;
      }
      
      .user-header {
        flex-direction: column;
        align-items: center;
        margin-bottom: 25px;
        text-align: center;
        
        .avatar-container {
          margin-right: 0;
          margin-bottom: 20px;
        }
        
        .user-info {
          h2 {
            font-size: 24px;
          }
        }
      }
      
      :deep(.el-form) {
        .el-form-item {
          margin-bottom: 20px;
        }
      }
    }
  }
}
</style> 